/**
 * 导入公共逻辑
 */
const {
  BASE_API
} = process.env;

import { enter2Br, aesDecode } from '@/utils/string';
import axios from 'axios';
import store from '../store';
import { getToken } from '@/utils/auth';
import { SECRET_KEY } from '@/utils/const';
import ElMessage from '@/utils/message';

export default {
  data() {
    return {
      loading: false,
      CancelAxios: null,
      maxVirtualPercent: 90,
      timer: '',
      uploadPercent: 0,
      isLt5M: false,
      fileName: ''
    };
  },
  methods: {
    getLimitFileSize() {
      return this.limitFileSize || 50;
    },
    importList(service, url, formData, getListfun, source) {
      this.loading = true;
      if (!this.titleBg) {
        if (this.beforeProp) {
          this.isLt5M = this.fileSize / 1024 / 1024 < this.getLimitFileSize();
        }
        if (!this.isLt5M && this.limitNum) { // 判断文件的大小以及文件的名称
          this.$message.error(`上传的文件不能超过${this.getLimitFileSize()}MB且文件名称不得超过50个字!`);
          this.loading = false;
          if (this.timer) clearInterval(this.timer); // 清除虚拟进度
          return true;
        } else if (!this.isLt5M) {
          this.$message.error(`上传的文件不能超过${this.getLimitFileSize()}MB!`);
          this.$emit('onError', `上传的文件不能超过${this.getLimitFileSize()}MB!`);
          this.loading = false;
          if (this.timer) clearInterval(this.timer); // 清除虚拟进度
          return true;
        } else if (this.limitNum) {
          ElMessage.warning('文件名称超过100个字，请修改后再试');
          this.loading = false;
          if (this.timer) clearInterval(this.timer); // 清除虚拟进度
          return true;
        }
      } else {
        if (!this.isUpload) {
          return false;
        }
      }
      this.$emit('upProgress');
      service.post(url, formData, {
        cancelToken: source.token || null
      }).then((res) => {
        const { data: { code, status, data }} = res;
        let { data: { message }} = res;
        // 只有有字段提示的才需要左对齐
        const textLeft = /\[/.test(message);
        if (textLeft) {
          message = message.split('\r\n').map(item => {
            return '<span style="display:block;max-width:1000px;">' + item + '</span>';
          }).join('<br/>');
        }
        this.$emit('onComplate', message);
        this.$emit('complateSetData', { data, fileName: this.fileName });
        if (Number(code) === 200 && status) {
          this.loading = false;
          this.fileNameCopy = this.fileName;
          if (!this.hideConfirm) {
            if (this.timer) clearInterval(this.timer); // 清除虚拟进度
            this.uploadPercent = 100; // 确保无总大小时还显示100%完成
            this.$confirm(message, '', {
              confirmButtonText: '确定',
              iconClass: 'charge-icon-success',
              customClass: 'charge-message-box',
              type: 'success',
              center: true
            }).then(() => {
              if (this.timer) clearInterval(this.timer); // 清除虚拟进度
              this.uploadPercent = 0; // 上传完后清除进度条
              this.loading = false;
              if (getListfun) getListfun();
            }).catch(() => {
              this.loading = false;
              if (this.timer) clearInterval(this.timer); // 清除虚拟进度
              this.uploadPercent = 0; // 上传完后清除进度条
              if (getListfun) getListfun();
            });
          } else {
            this.$emit('onSucess', message);
          }
        } else if (Number(code) === 401) {
          this.loading = false;
          this.$confirm(
            '当前登录已过期，请重新登录',
            '',
            {
              confirmButtonText: '重新登录',
              type: 'warning',
              customClass: 'del-message',
              iconClass: 'del-icon',
              showCancelButton: false,
              center: true
            }
          ).then(() => {
            this.loading = false;
            store.dispatch('FedLogOut').then(() => {
              location.reload(); // 为了重新实例化vue-router对象 避免bug
            });
          }).catch(() => {
            if (this.timer) clearInterval(this.timer); // 清除虚拟进度
            this.uploadPercent = 0; // 上传完后清除进度条
            this.loading = false;
            return;
          });
        } else {
          this.loading = false;
          this.uploadPercent = 100; // 在导入失败后进度条总还是100
          this.$emit('onError', message);
          if (!this.hideConfirm) {
            this.$confirm(enter2Br(message), '', {
              confirmButtonText: '确定',
              showCancelButton: false,
              showClose: true,
              type: 'warning',
              center: true,
              iconClass: 'charge-icon',
              customClass: `charge-message-box ${textLeft ? 'text-left-box' : ''}`,
              dangerouslyUseHTMLString: true
            }).then(() => {
              if (this.timer) clearInterval(this.timer); // 清除虚拟进度
              this.uploadPercent = 0; // 上传完后清除进度条
              this.loading = false;
              this.fileList = [];
              if (this.isSealing && this.isSealingCompolete) {
                this.isSealingCompolete();
              }
            }).catch(() => {
              if (this.timer) clearInterval(this.timer); // 清除虚拟进度
              this.uploadPercent = 0; // 上传完后清除进度条
              this.loading = false;
              this.fileList = [];
              if (this.isSealing && this.isSealingCompolete) {
                this.isSealingCompolete();
              }
            });
          }
        }
      }).catch((err) => {
        this.loading = false;
        if (this.timer) clearInterval(this.timer); // 清除虚拟进度
        this.uploadPercent = 0; // 上传完后清除进度条
        let errMsg = typeof err === 'object' ? err.message : err;
        if (errMsg.indexOf('timeout') >= 0) {
          errMsg = '文件较大，拼命导入中，请半小时后进入系统查看导入结果';
        }
        if (errMsg === 'Network Error') {
          this.$message.warning('网络错误！请检查网络状态...');
        }
        this.$emit('onError', errMsg || '请求失败');
        if (this.errorFileListChange) this.errorFileListChange(formData, err);
      });
    },
    serviceToken(service) {
      service.interceptors.request.use(
        config => {
          const token = store.getters.token || getToken();
          if (token) {
            config.headers.common['token'] = token;
          }
          return config;
        },
        error => {
          console.log(error);
          Promise.reject(error);
        }
      );
      service.interceptors.response.use(response => {
        if (response && response.data && typeof response.data === 'string') {
          const decodeStr = aesDecode(response.data, SECRET_KEY);
          try {
            response.data = typeof decodeStr === 'string' ? JSON.parse(decodeStr) : decodeStr;
          } catch (error) {
            response.data = decodeStr;
          }
        }
        return response;
      });
    },
    beforeUpload(file) {
      this.$emit('beforeUpload', { file });
      if (!this.titleBg) {
        const fileName = file.name;
        const fileNameTemp = file.name.replace(/\.xl(s|s[xmb]|t[xm]|am)$/, '');
        fileNameTemp.length > 100 ? this.limitNum = true : this.limitNum = false; // 判断文件名的长度
        this.isLt5M = file.size / 1024 / 1024 < this.getLimitFileSize();
        if (!this.isLt5M) {
          this.$message.error(`上传的文件不能超过${this.getLimitFileSize()}MB!`);
          this.$emit('onError', `上传的文件不能超过${this.getLimitFileSize()}MB!`);
        } else {
          this.fileName = fileName;
        }
        return this.isLt5M;
      } else {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isGIF = file.type === 'image/gif';
        const isLt2M = file.size / 1024 / 1024 < 2;
        this.isUpload = true;
        if (!isJPG && !isPNG && !isGIF) {
          this.$message.error('图片只能是 JPG/PNG/GIF 格式!');
          this.isUpload = false;
          return false;
        }
        if (!isLt2M) {
          this.$message.error('图片大小不能超过 2MB!');
          this.isUpload = false;
          return false;
        }
        return (isJPG || isPNG || isGIF) && isLt2M;
      }
    },
    uploadFileMethod(param) {
      const fileObject = param.file;
      const formData = new FormData();
      formData.append('fileData', fileObject);
      if (this.uploadId && this.uploadId !== '') {
        formData.append('uploadId', this.uploadId);
      }
      if (this.fileName) {
        formData.append('fileName', this.fileName);
      }
      if (this.extendParams) {
        for (const key in this.extendParams) {
          if (this.extendParams.hasOwnProperty(key)) {
            const element = this.extendParams[key];
            formData.append(key, element);
          }
        }
      }
      this.toUploadHttp(formData);
    },
    toUploadHttp(formData) {
      const that = this;
      this.timer = setInterval(() => { // 开始虚拟进度
        if (this.uploadPercent <= this.maxVirtualPercent) this.uploadPercent += 1;
        else clearInterval(this.timer);
      }, 80);
      var source = axios.CancelToken.source();
      const service = axios.create({
        baseURL: BASE_API, // api 的 base_url
        timeout: 3600000, // 请求超时时间
        // timeout: 60000,
        headers: {
          'Content-Type': 'multipart/form-data;'
        },
        onUploadProgress: function(progressEvent) { // 获取进度条
          if (progressEvent.lengthComputable) {
            // if (that.timer) clearInterval(that.timer);
            const lastPercent = that.uploadPercent ? that.uploadPercent : 0;
            const total = progressEvent.total;
            const loaded = progressEvent.loaded;

            const uploadPercent = parseInt(loaded / total * 100);
            that.uploadPercent = lastPercent >= uploadPercent ? lastPercent : uploadPercent;
            if (that.uploadPercent === 100) {
              setTimeout(() => {
                that.uploadPercent = 0;
              }, 1000);
            }
          }
        }
      });
      this.cancelAxios = source;
      this.serviceToken(service);
      this.importList(service, this.importApi, formData, this.getList, source);
    },
    cancelHttp(msg = '请求已取消') {
      if (this.cancelAxios) {
        this.cancelAxios.cancel(msg);
      }
    }
  }
};
